﻿namespace API.Filters;

/// <summary>
/// 属性检查过滤器
/// </summary>
public class RoleChangeCheckFilter
 : IAsyncActionFilter
{
    private readonly ILogger<ResponseWrapperFilter> _logger;
    private readonly IUserBLL _userBLL;
    /// <summary>
    /// 登陆通道
    /// </summary>

    /// <summary>
    /// 响应捕捉器构造函数
    /// </summary>
    public RoleChangeCheckFilter(ILogger<ResponseWrapperFilter> logger,IUserBLL userBLL)
    {
        _logger = logger;
        _userBLL = userBLL;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    /// <param name="next"></param>
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var controllerActionDescriptor = (ControllerActionDescriptor)context.ActionDescriptor;
        var isDefined = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
            .Any(a => a.GetType().Equals(typeof(AllowAnonymousAttribute))) || controllerActionDescriptor.ControllerTypeInfo.GetCustomAttributes(inherit: true)
            .Any(a => a.GetType().Equals(typeof(AllowAnonymousAttribute)));
        if (isDefined)
        {
            await next();
            return;
        }
        var userId = Convert.ToInt32(context.HttpContext.User.FindFirstValue("user_id"));
        User user = _userBLL.Get(x => x.UserId == userId);
        var loginrole = await RedisStaticHelper.GetAsync<int>($"loginrole_{user.Account}");
        if (user.RoleId != loginrole)
        {
            context.Result = new OkObjectResult(new ResultModel { code = -1001, msg = "用户权限异常请重新登录！" });
            return;
        }
        await next();
    }

}
